﻿using EpubReader.Entity;
using Ionic.Zip;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;

namespace EpubReader
{
    public class EpubReaders
    {
        public static string OEBPS = "OEBPS";
        /// <summary>
        /// 获取到的压缩属性
        /// </summary>
        public static ZipFile ZipFileModel { get; set; }
        public static List<ChapterEntity> LoadEpubFile(string path)
        {
            if (!File.Exists(path))
            {
                throw new Exception("文件不存在！");
            }
            ZipFile zipEntries = ZipFile.Read(path);
            ZipFileModel = zipEntries;
            ZipEntry zipEntry = zipEntries.Entries.FirstOrDefault(e => e.FileName.Contains(@".ncx"));// StringComparison.InvariantCultureIgnoreCase));

            if (zipEntry != null)
            {

                MemoryStream memoryStream = new MemoryStream();
                zipEntry.Extract(memoryStream);

                memoryStream.Position = 0;

                DataSet ds = new DataSet();
                XmlReaderSettings setting = new XmlReaderSettings();
                setting.DtdProcessing = DtdProcessing.Parse;
                ds.ReadXml(XmlReader.Create(memoryStream, setting));
                DataTable dataTable = ds.Tables["navLabel"];
                ChapterEntityList = new List<ChapterEntity>();
                for (int index = 0; index < dataTable.Rows.Count; index++)
                {
                    var dataf = dataTable.Rows[index].ItemArray;
                    ChapterEntity chapterEntity = new ChapterEntity();
                    chapterEntity.ChapterId = dataf[1].ToString();
                    chapterEntity.ChapterText = dataf[0].ToString();
                    ChapterEntityList.Add(chapterEntity);
                }
                DataTable contentTable = ds.Tables["content"];
                for (int index = 0; index < contentTable.Rows.Count; index++)
                {
                    var dataf = contentTable.Rows[index].ItemArray;
                    ChapterEntityList.ForEach(p =>
                    {
                        if (p.ChapterId == dataf[1].ToString())
                        {
                            p.ChapterSrc = dataf[0].ToString();
                            GetMainContent(p);
                            return;
                        }
                    });
                }

            }
            return ChapterEntityList;
        }
        private static void GetMainContent(ChapterEntity chapterEntity)
        {
            if (!string.IsNullOrWhiteSpace(chapterEntity.ChapterSrc))
            {
                ZipEntry zipEntry = ZipFileModel.Entries.FirstOrDefault(e => e.FileName.Contains(chapterEntity.ChapterSrc));
                MemoryStream memoryStream = new MemoryStream();
                zipEntry.Extract(memoryStream);
                memoryStream.Position = 0;
                //get stream just in case we have a namespace prefix
                var containerXml = XElement.Load(memoryStream);
                chapterEntity.Content = containerXml.Value;
                memoryStream.Position = 0;
                var sr = new System.IO.StreamReader(memoryStream);
                var tmpXMLStream = sr.ReadToEnd();
                chapterEntity.ContentSource = tmpXMLStream;
                //XDocument xDocument = XDocument.Parse(tmpXMLStream);
            }
        }
        public static List<ChapterEntity> ChapterEntityList { get; set; }
        static void GetChapter(XDocument xDocument)
        {
            if (ChapterEntityList == null)
                ChapterEntityList = new List<ChapterEntity>();
            if (xDocument.NextNode == null)
                return;

        }

    }
}
